package edu.pk.mc.breakthebrick;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;

public class ScoreInfoServiceXMLParser {

private static final String ns = null;
	
	public ScoreDTO[] parse(InputStream is) throws XmlPullParserException, IOException{
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(is, null);
        parser.nextTag();
        return readFeed(parser);
	}
	
	private ScoreDTO[] readFeed(XmlPullParser parser) throws XmlPullParserException, IOException{
	    List<ScoreDTO> cities = new ArrayList<ScoreDTO>();
		parser.require(XmlPullParser.START_TAG, ns, "scores");
	    while (parser.next() != XmlPullParser.END_TAG) {
	        if (parser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        cities.add(readCity(parser));
	    }
	    ScoreDTO [] citiesArray = new ScoreDTO[cities.size()];
	    citiesArray = cities.toArray(citiesArray);
	    return citiesArray;
	}
	
	private ScoreDTO readCity(XmlPullParser parser) throws XmlPullParserException, IOException {
	    parser.require(XmlPullParser.START_TAG, ns, "highscore");
		int id = 0;
		int score = 0;
	    while (parser.next() != XmlPullParser.END_TAG) {
	        if (parser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        String tagName = parser.getName();
	        if (tagName.equals("id")) {
	            id = Integer.parseInt(readTag(parser, "id"));
	        } else if (tagName.equals("score")) {
	            score =Integer.parseInt( readTag(parser,"score"));
	        } 
	    }
	    return new ScoreDTO(id, score);
	}
	
	private String readTag(XmlPullParser parser, String tagName) throws XmlPullParserException, IOException{
		parser.require(XmlPullParser.START_TAG, ns, tagName);
		String text = readText(parser);
		parser.require(XmlPullParser.END_TAG, ns, tagName);
		return text;		
	}
	
	private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
	    String result = "";
	    if (parser.next() == XmlPullParser.TEXT) {
	        result = parser.getText();
	        parser.nextTag();
	    }
	    return result;
	}
}
